<?php

namespace App\V3\V3_1\Controllers;

use App\V3\V3_1\Models\KuaidiModel;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Validator;

class KuaidiController extends Controller
{
    /**
     * 获取快递公司列表
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/3 10:29
     * @return \Illuminate\Http\JsonResponse
     */
    public function list()
    {
        return $this->success(
            KuaidiModel::select(
                'id',
                'company_name',
                'company_code',
            )->where('company_type_name', 'like', '国内%')->get()->toArray()
        );
    }

    public function newList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => ''
            ]);
        }

        $keyword = $request->keyword;

        $result = KuaidiModel::where(function($query) use ($keyword) {
            $query->orWhere('company_name', 'like', '%'.$keyword.'%');
            $query->orWhere('company_code', 'like', '%'.$keyword.'%');
        })
            ->orderBy('id', 'ASC')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);

        return response()->json([
            'code' => 0,
            'msg' => 'success',
            'data' => $result
        ]);
    }
}
